<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="`${isUpdate ? '编辑' : '新增'}菜单`"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { geAdminMenusList } from '@/api/admin/admin_menus';
  import { createAdminMenus, updateAdminMenus} from "@/api/admin/admin_menus";
  import {useMessage} from "@/hooks/web/useMessage";

  defineOptions({ name: 'MenuDrawer' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const profile = ref();
  const { createMessage } = useMessage()

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    profile.value = data.record;

    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      let data = null
      if (unref(isUpdate)) {
        data = (await updateAdminMenus({ ...values, id: profile.value.id })) as any
      } else {
        data = (await createAdminMenus(values)) as any
      }

      if (!data.code) {
        createMessage.success(`设置成功！`)
        emit('success', {})
        closeDrawer();
        emit('success');
      } else {
        createMessage.warn(`设置失败！`)
      }

    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
